#include "player.h"
#include "keyboard.h"
#include "log.h"
#include "settings.h"
#include "game.h"

cPlayer::cPlayer()
{
    m_x = 128;
    m_y = 128;
    m_velx = 0;
    m_vely = 0;
    m_baseSpeed = 500;
    m_slowSpeed = 250;
    m_lives = 3;
    m_reloadTime = 10;
    m_reloadAt = 0;
    m_slow = false;
    m_shoot = false;
    m_canShoot = true;

    m_hitbox = new Hitbox();
    m_hitbox->x = (int)m_x;
    m_hitbox->y = (int)m_y;
    m_hitbox->rad = 64;

    m_texture.loadTextureFromFile("img/test.png");
}

cPlayer::~cPlayer()
{
    //m_texture.freeTexture();
}

void cPlayer::checkKeys()
{
    if (keyboard::keyDown("KEY_UP") || keyboard::keyUp("KEY_DOWN"))
        m_vely -= 1;
    if (keyboard::keyDown("KEY_LEFT") || keyboard::keyUp("KEY_RIGHT"))
        m_velx -= 1;
    if (keyboard::keyDown("KEY_DOWN") || keyboard::keyUp("KEY_UP"))
        m_vely += 1;
    if (keyboard::keyDown("KEY_RIGHT") || keyboard::keyUp("KEY_LEFT"))
        m_velx += 1;

    if (keyboard::keyDown("KEY_SLOW"))
        m_slow = true;
    if (keyboard::keyUp("KEY_SLOW"))
        m_slow = false;

    if (keyboard::keyDown("KEY_SHOOT"))
        m_shoot = true;
    if (keyboard::keyUp("KEY_SHOOT"))
        m_shoot = false;
}

void cPlayer::movePlayer(int frameTime)
{
    if (cGame::instance().isPaused())
        return;

    if (m_slow)
    {
        m_x += m_slowSpeed * m_velx * frameTime / 1000.f;
        m_y += m_slowSpeed * m_vely * frameTime / 1000.f;
    }
    else
    {
        m_x += m_baseSpeed * m_velx * frameTime / 1000.f;
        m_y += m_baseSpeed * m_vely * frameTime / 1000.f;
    }

    if (m_x < m_hitbox->rad)
        m_x = m_hitbox->rad;

    if (m_x > (getInt("WINDOW_WIDTH") - m_hitbox->rad))
        m_x = getInt("WINDOW_WIDTH") - m_hitbox->rad;

    if (m_y < m_hitbox->rad)
        m_y = m_hitbox->rad;

    if (m_y > (getInt("WINDOW_HEIGHT") - m_hitbox->rad))
        m_y = getInt("WINDOW_HEIGHT") - m_hitbox->rad;

    m_hitbox->x = (int)m_x;
    m_hitbox->y = (int)m_y;
}

void cPlayer::shoot()
{
    if (cGame::instance().currentMap()->time() > m_reloadAt)
        m_canShoot = true;

    if (m_canShoot)
    {
        cGame::instance().currentMap()->createBullet(x(), y() - m_hitbox->rad, 1500, 270);
        m_canShoot = false;
        m_reloadAt = cGame::instance().currentMap()->time() + m_reloadTime;
    }
}

cTexture* cPlayer::texture()
{
    return &m_texture;
}

Hitbox* cPlayer::hitbox()
{
    return m_hitbox;
}

void cPlayer::update(int frameTime)
{
    checkKeys();
    movePlayer(frameTime);
    if (m_shoot)
        shoot();

    //if (m_velx != 0 || m_vely != 0)
        //log(LOG_DEBUG, "x: %d y: %d\n", (int)m_x, (int)m_y);
}

int cPlayer::x()
{
    return (int)m_x;
}

int cPlayer::y()
{
    return (int)m_y;
}
